#!/usr/bin/python3
# -*- coding: utf-8 -*-
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, DestroyModelMixin

# basename- 用于创建的 URL 名称的基础。
# action- 当前操作的名称（例如:list create）。
# detail- 布尔值，指示当前操作是否配置为列表或详细信息视图。
# suffix- 视图集类型的显示后缀 - 镜像属性。detail
# name- 视图集的显示名称。此参数与 互斥。suffix
# description- 视图集的单个视图的显示说明。
from rest_framework.settings import api_settings


class CreateRetrieveViewSet(viewsets.ReadOnlyModelViewSet):
    lookup_field = 'pk'

    # , permission_classes=[IsAdminOrIsSelf]

    @action(detail=False, methods=['get', 'post'], name="addItem", description="新增")
    def addItem(self, request, *args, **kwargs):
        return CreateModelMixin.create(self, request, args, kwargs)

    # 需要嵌入详情里面
    @action(detail=True, methods=['post'], name="updateItem", description="通过主键更新")
    def updateItem(self, request, *args, **kwargs):
        return UpdateModelMixin.update(self, request, args, kwargs)

    # 参数“pk”放在url和放在请求体里面都可以更新
    @action(detail=False, methods=['post'], name="updateBypk", description="通过主键更新")
    def updateBypk(self, request, *args, **kwargs):
        self.lookup_field = 'pk'
        if "pk" not in request.data:
            pk = request.query_params.get('pk', None)
            kwargs = {"pk": pk}
            self.kwargs = {"pk": pk}
        else:
            self.kwargs = {"pk": request.data["pk"]}
            kwargs = {"pk": request.data["pk"]}
        return UpdateModelMixin.update(self, request, args, kwargs)

    # 参数“pk”放在url和放在请求体里面都可以删除
    # 如果需要后面携带参数 pk=xx 这种 detail设置为False
    @action(detail=False, methods=['post'], name="deleteItem", description="通过主键删除")
    def deleteBypk(self, request, *args, **kwargs):
        self.lookup_field = 'pk'
        pk = None
        if "pk" not in request.data:
            pk = request.query_params.get('pk', None)
            self.kwargs = {'pk': pk}
        else:
            pk = request.data["pk"]
            self.kwargs = {"pk": request.data["pk"]}
        return DestroyModelMixin.destroy(self, request, pk)

    @action(detail=True, methods=['post'], name="deleteByPathVar", description="通过路径携带id进行删除")
    def deleteItem(self, request, pk=None):
        return DestroyModelMixin.destroy(self, request, pk)

    @classmethod
    def get_success_headers(self, data):
        try:
            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}

    @classmethod
    def perform_update(self, serializer):
        serializer.save()

    @classmethod
    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)

    @classmethod
    def perform_destroy(self, instance):
        instance.delete()
